﻿using Microsoft.Extensions.Caching.Memory;
using System.Collections;
using System.Reflection;
using System.Text.RegularExpressions;

namespace D.Util.UtilCache
{
    /// <summary>
    /// Microsoft.Extensions.Caching.Abstractions
    /// Microsoft.Extensions.Caching.Memory
    /// Microsoft.Extensions.DependencyInjection.Abstractions
    /// </summary>
    public class CacheService : ICacheService
    {
        private IMemoryCache _memoryCache = new MemoryCache(new MemoryCacheOptions());

        /// <summary>
        /// 
        /// </summary>
        public long Del(params string[] key)
        {
            foreach (var k in key)
            {
                _memoryCache.Remove(k);
            }
            return key.Length;
        }

        /// <summary>
        /// 
        /// </summary>
        public async Task<long> DelAsync(params string[] key)
        {
            foreach (var k in key)
            {
                _memoryCache.Remove(k);
            }

            return await Task.FromResult(key.Length);
        }

        /// <summary>
        /// 
        /// </summary>
        public async Task<long> DelByPatternAsync(string pattern)
        {
            if (string.IsNullOrEmpty(pattern))
                return default;

            pattern = Regex.Replace(pattern, @"\{.*\}", "(.*)");

            var keys = GetAllKeys().Where(k => Regex.IsMatch(k, pattern));

            if (keys != null && keys.Any())
            {
                return await DelAsync(keys.ToArray());
            }

            return default;
        }

        /// <summary>
        /// 
        /// </summary>
        public bool Exists(string key)
        {
            return _memoryCache.TryGetValue(key, out _);
        }

        /// <summary>
        /// 
        /// </summary>
        public async Task<bool> ExistsAsync(string key)
        {
            return await Task.FromResult(_memoryCache.TryGetValue(key, out _));
        }

        /// <summary>
        /// 
        /// </summary>
        public string Get(string key)
        {
            return _memoryCache.Get(key)?.ToString();
        }
         
        /// <summary>
        /// 
        /// </summary>
        public async Task<string> GetAsync(string key)
        {
            return await Task.FromResult(Get(key));
        }
        /// <summary>
        /// 
        /// </summary>
        public async Task<T> GetAsync<T>(string key)
        {
            return await Task.FromResult(Get<T>(key));
        }
        /// <summary>
        /// 
        /// </summary>
        public bool Set(string key, object? value)
        {
            _memoryCache.Set(key, value);
            return true;
        }
        /// <summary>
        /// 
        /// </summary>
        public bool Set(string key, object? value, TimeSpan expire)
        {
            _memoryCache.Set(key, value, expire);
            return true;
        }
        /// <summary>
        /// 
        /// </summary>
        public async Task<bool> SetAsync(string key, object? value)
        {
            Set(key, value);
            return await Task.FromResult(true);
        }
        /// <summary>
        /// 
        /// </summary>
        public async Task<bool> SetAsync(string key, object? value, TimeSpan expire)
        {
            Set(key, value, expire);
            return await Task.FromResult(true);
        }
        /// <summary>
        /// 
        /// </summary>
        private List<string> GetAllKeys()
        {
            const BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic;
            var entries = _memoryCache.GetType().GetField("_entries", flags).GetValue(_memoryCache);
            var cacheItems = entries as IDictionary;
            var keys = new List<string>();
            if (cacheItems == null) return keys;
            foreach (DictionaryEntry cacheItem in cacheItems)
            {
                if (cacheItem.Key != null)
                    keys.Add(cacheItem.Key.ToString());
            }
            return keys;
        }

        /// <summary>
        /// 取得缓存数据
        /// </summary>
        /// <typeparam name="T">类型值</typeparam>
        /// <param name="key">关键字</param>
        /// <returns></returns>
        public T? Get<T>(string key)
        {
            if (string.IsNullOrWhiteSpace(key))
                throw new ArgumentNullException(nameof(key));
            T? value;
            _memoryCache.TryGetValue<T>(key, out value);
            return value;
        }

        /// <summary>
        /// 设置缓存(永不过期)
        /// </summary>
        /// <param name="key">关键字</param>
        /// <param name="value">缓存值</param>
        public void Set_NotExpire<T>(string key, T value)
        {
            if (string.IsNullOrWhiteSpace(key))
                throw new ArgumentNullException(nameof(key));

            T v;
            if (_memoryCache.TryGetValue(key, out v))
                _memoryCache.Remove(key);
            _memoryCache.Set(key, value);
        }

        /// <summary>
        /// 设置缓存(滑动过期:超过一段时间不访问就会过期,一直访问就一直不过期)
        /// </summary>
        /// <param name="key">关键字</param>
        /// <param name="value">缓存值</param>
        public void Set_SlidingExpire<T>(string key, T value, TimeSpan span)
        {
            if (string.IsNullOrWhiteSpace(key))
                throw new ArgumentNullException(nameof(key));

            T v;
            if (_memoryCache.TryGetValue(key, out v))
                _memoryCache.Remove(key);
            _memoryCache.Set(key, value, new MemoryCacheEntryOptions()
            {
                SlidingExpiration = span
            });
        }

        /// <summary>
        /// 设置缓存(绝对时间过期:从缓存开始持续指定的时间段后就过期,无论有没有持续的访问)
        /// </summary>
        /// <param name="key">关键字</param>
        /// <param name="value">缓存值</param>
        public void Set_AbsoluteExpire<T>(string key, T value, TimeSpan span)
        {
            if (string.IsNullOrWhiteSpace(key))
                throw new ArgumentNullException(nameof(key));

            T v;
            if (_memoryCache.TryGetValue(key, out v))
                _memoryCache.Remove(key);
            _memoryCache.Set(key, value, span);
        }

        /// <summary>
        /// 设置缓存(绝对时间过期+滑动过期:比如滑动过期设置半小时,绝对过期时间设置2个小时，那么缓存开始后只要半小时内没有访问就会立马过期,如果半小时内有访问就会向后顺延半小时，但最多只能缓存2个小时)
        /// </summary>
        /// <param name="key">关键字</param>
        /// <param name="value">缓存值</param>
        public void Set_SlidingAndAbsoluteExpire<T>(string key, T value, TimeSpan slidingSpan, TimeSpan absoluteSpan)
        {
            if (string.IsNullOrWhiteSpace(key))
                throw new ArgumentNullException(nameof(key));

            T v;
            if (_memoryCache.TryGetValue(key, out v))
                _memoryCache.Remove(key);
            _memoryCache.Set(key, value, new MemoryCacheEntryOptions()
            {
                SlidingExpiration = slidingSpan,
                AbsoluteExpiration = DateTimeOffset.Now.AddMilliseconds(absoluteSpan.TotalMilliseconds)
            });
        }

        /// <summary>
        /// 移除缓存
        /// </summary>
        /// <param name="key">关键字</param>
        public void Remove(string key)
        {
            if (string.IsNullOrWhiteSpace(key))
                throw new ArgumentNullException(nameof(key));

            _memoryCache.Remove(key);
        }

        /// <summary>
        /// 释放
        /// </summary>
        public void Dispose()
        {
            if (_memoryCache != null)
                _memoryCache.Dispose();
            GC.SuppressFinalize(this);
        } 
    }
}